package com.cqcomponents.servlets;

import java.io.IOException;
import java.util.Iterator;

import javax.jcr.Node;
import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.servlets.SlingSafeMethodsServlet;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.day.cq.wcm.api.Page;

@SlingServlet(paths = { "/bin/cqcomponents/pagenodes" })
public class PageAndNodesListServlet extends SlingSafeMethodsServlet {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	/**
	 * 
	 */
	private static final long serialVersionUID = -3802536443904502295L;

	@Override
	protected void doGet(SlingHttpServletRequest request,
			SlingHttpServletResponse response) throws ServletException,
			IOException {
		String path = request.getParameter("path");
		if (StringUtils.isBlank(path)) {
			path = "/content";
		}
		Resource resource = request.getResourceResolver().getResource(path);

		// Iterate over all children
		Iterator<Resource> iterator = resource.getResourceResolver()
				.listChildren(resource);

		JSONArray result = new JSONArray();
		try {
			while (iterator.hasNext()) {

				Resource childResource = iterator.next();
				Node childNode = (childResource.adaptTo(Node.class));

				String iconCls = "unstructured";
				String name = childNode.getName();
				String text = name;
				String type = childNode.getPrimaryNodeType().getName();
				boolean leaf = !childNode.hasNodes();
				if (leaf) {
					// Ignore leaf
					continue;
				}
				Page childPage = childResource.adaptTo(Page.class);
				if (childPage != null) {
					iconCls = "page";
				}

				JSONObject object = new JSONObject();
				object.put("name", name);
				object.put("type", type);
				object.put("text", text);
				object.put("iconCls", iconCls);
				object.put("leaf", leaf);

				result.put(object);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		response.setContentType("application/json");
		response.getWriter().write(result.toString());
	}
}
